package com.it.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.it.reggie.common.Result;
import com.it.reggie.entity.Category;
import com.it.reggie.service.ICategoryService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @author:cyh
 * @data:2022/12/15 9:46
 */

/**
 * 编写元数据对象处理器，
 *  在此类中统一为公共字段赋值，此类需要实现MetaObjectHandler接口。
 */
@Api(tags = "分类管理")
@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    ICategoryService categoryService;

    @GetMapping("/page")
    public Result<Page> queryPage(Integer page,Integer pageSize){
        Page<Category> categoryPage = new Page<>(page, pageSize);
        categoryService.page(categoryPage);
        return Result.success(categoryPage);
    }

    @PostMapping
    public Result save(HttpServletRequest request, @RequestBody Category category){
//        category.setCreateTime(LocalDateTime.now());
//        category.setUpdateTime(LocalDateTime.now());
//        Long empId=(Long) request.getSession().getAttribute("employee");
//        category.setCreateUser(empId);
//        category.setUpdateUser(empId);
        boolean save = categoryService.save(category);
        return save?Result.success("添加成功"):Result.filed("添加失败");
    }

    @DeleteMapping
    public Result deleteById(Long id){
        boolean result=categoryService.deleteById(id);
        return result?Result.success("删除成功"):Result.filed("删除失败,该分类下有对应的菜品或套餐");
    }

    @PutMapping
    public Result updateById(@RequestBody Category category){
        boolean update = categoryService.updateById(category);
        return update?Result.success("修改成功"):Result.filed("修改失败");
    }

    //查询菜品分类
    @GetMapping("/list")
    public Result<List<Category>> queryDishCategory(Integer type){
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(type!=null, Category::getType, type);
        wrapper.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);
        List<Category> categoryList = categoryService.list(wrapper);
        return Result.success(categoryList);
    }
}
